package 数据结构.章节09._164_两个栈实现队列;

import java.util.Stack;

/**
 * @author 挚爱之夕
 * @date 2021/10/13 - 10 - 13 - 19:33
 * @Description: 数据结构.章节09
 * @Version: 1.0
 */
public class SpecialQueue<T> {
    Stack<T> stack1 = new Stack<>();
    Stack<T> stack2 = new Stack<>();

    public void enqueue(T e) {
        if (stack1.isEmpty()) {
            move(stack2, stack1);
        }
        stack1.push(e);
    }

    public T dequeue() {
        if (stack2.isEmpty()) {
            move(stack1, stack2);
        }
        return stack2.pop();
    }

    public T peek() {
        if (stack2.isEmpty()) {
            move(stack1, stack2);
        }
        return stack2.peek();
    }

    public boolean isEmpty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    public int size() {
        return stack1.size() == 0 ? stack2.size() : stack1.size();
    }

    private void move(Stack<T> source, Stack<T> target) {
        while (!source.isEmpty()) {
            T element = source.pop();
            target.push(element);
        }
    }
}
